package com.arykow.engine.onwebapp.server;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class FeedParser {

	public void parse(String url, FeedParserListener listener) {
		SyndFeed feed = null;
		try {
			SyndFeedInput input = new SyndFeedInput();

			HttpURLConnection connection = HttpURLConnection.class.cast(new URL(url).openConnection());
			connection.setRequestProperty("User-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.5 Safari/534.55.3");

			feed = input.build(new XmlReader(connection));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (feed != null) {
			{
				String title = feed.getTitle();
				String link = feed.getLink();
				listener.listenStart(title, link, feed.getEntries().size());
			}
			int index = 0;
			for (Object object : feed.getEntries()) {
				SyndEntry entry = SyndEntry.class.cast(object);

				String id = parseEntryId(entry);
				String title = parseEntryTitle(entry);
				String description = parseEntryDescription(entry);
				String link = parseEntryLink(entry);
				Date publishedDate = parseEntryPublishedDate(entry);
				listener.listenEntry(index++, id, title, description, link, publishedDate);
			}
			listener.listenStop();
		}

	}

	private Date parseEntryPublishedDate(SyndEntry entry) {
		Date value = entry.getPublishedDate();
		if (value == null) {
			value = new Date();
		}
		return value;
	}

	private String parseEntryLink(SyndEntry entry) {
		String value = null;
		try {
			URL myurl = new URL(entry.getUri());
			if (myurl != null) {
				value = entry.getUri();
			}
		} catch (Exception e) {
		}
		if (value == null) {
			value = entry.getLink();
		}
		if (value == null) {
			System.out.println(entry.toString());
			value = "";
		}
		return value;
	}

	private String parseEntryDescription(SyndEntry entry) {
		String value = null;
		if (entry.getContents() != null) {
			for (Object objectContent : entry.getContents()) {
				SyndContent content = SyndContent.class.cast(objectContent);
				if (content != null && content.getValue() != null) {
					value = content.getValue();
					break;
				}
			}
		}
		if (value == null) {
			if (entry.getDescription() != null) {
				value = entry.getDescription().getValue();
			}
		}
		if (value == null) {
			value = "";
		}
		return value;
	}

	private String parseEntryTitle(SyndEntry entry) {
		String value = entry.getTitle();
		if (value == null) {
			value = "";
		}
		return value;
	}

	private String parseEntryId(SyndEntry entry) {
		String value = entry.getUri();
		if (value == null) {
			value = "";
		}
		return value;
	}

}
